package cn.dida.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.regex.Pattern;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.dida.util.ValidUtil;
import net.sf.json.JSONArray;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;

import cn.dida.exception.BizzException;
import cn.dida.model.HttpResponseBodyWrapper;
import cn.dida.model.Pageable;
import cn.dida.model.Pbc;
import cn.dida.model.UserSession;
import cn.dida.service.PbcService;
import cn.dida.service.QrcodeService;
import cn.dida.util.DateUtils;
import cn.dida.util.ExcelUtil;
import cn.dida.util.HttpClientUtil;
import cn.dida.util.NumberConvetUtil;

@Controller
public class QrcodeController extends BaseController {

	@Value("${upload.path.pic}")
	private String picStoragePath;
	
	@Value("${d.apis.url}")
	private String dApisurl;
	
	@Value("${d.apis.groupurl}")
	private String dApisgroupurl;
	
	@Value("${d.apis.token}")
	private String dApistoken;
	
	@Value("${qrcode.valid.url}")
	String qrcode_valid_url;
	
	//批量请求数量
	@Value("${qrcode.add.batchNumber}")
	private Long batchNumber;

	@Autowired
	private QrcodeService qrcodeService;
	
    @Autowired
    private PbcService pbcService;

	@GetMapping("/qrcode")
	public ModelAndView qrcode_list(HttpServletRequest request, Integer page) throws Exception {
		Map<String, Object> model = new HashMap<String, Object>();
		UserSession userSession = getUserSession(request);

		Map<String, Object> paramMap = getSimpleRequestParamMap(request);

		page = (page == null || page < 1) ? 1 : page;

		Pageable<Map<String, Object>> pagelist = qrcodeService.queryAllQrcodeByCompnayID(userSession.getCompanyId(),
				paramMap, page);

		pagelist.setRquesturl(request, paramMap);

		model.put("pagelist", pagelist);

		for (String key : paramMap.keySet()) {
			model.put(key, paramMap.get(key));
		}

		return new ModelAndView("qrcode_list").addAllObjects(model);
	}

	@GetMapping("/qrcode/detail")
	public ModelAndView qrcode_detail_list(HttpServletRequest request,String  id,String proName, String qrId, Integer state, Integer page) throws Exception {
		Map<String, Object> model = new HashMap<String, Object>();
		UserSession userSession = getUserSession(request);
//
//		Map<String, Object> paramMap = getSimpleRequestParamMap(request);

		page = (page == null || page < 1) ? 1 : page;

		Pageable<Map<String, Object>> pagelist = qrcodeService.queryQrcodeDetailByID(userSession.getCompanyId(),
				id, proName,qrId,state, page);

		if (null != pagelist && pagelist.getResult().size() > 0) {
			for (int j = 0; j < pagelist.getResult().size(); j++) {
				Map<String, Object> tmap = pagelist.getResult().get(j);
				if(tmap.get("w_uuid")!=null&&tmap.get("w_uuid").toString().length()>0){
					tmap.put("show_code",tmap.get("w_uuid").toString());
				}else{
					tmap.put("show_code", NumberConvetUtil.baseString(NumberUtils.toLong(tmap.get("id").toString(), 0L),
							NumberConvetUtil.SIXTY_CONVET));
				}
			}

		}

//		pagelist.setRquesturl(request, paramMap);

		model.put("pagelist", pagelist);

//		for (String key : paramMap.keySet()) {
			model.put("id", id);
//		}
		model.put("proName", proName);
		model.put("qrId", qrId);
		model.put("state", state);

		return new ModelAndView("qrcode_detail_list").addAllObjects(model);
	}

	@GetMapping("/qrcode/binding")
	public ModelAndView qrcode_binding_show(HttpServletRequest request, Integer page) throws Exception {
		Map<String, Object> model = new HashMap<String, Object>();
		UserSession userSession = getUserSession(request);

		Map<String, Object> paramMap = getSimpleRequestParamMap(request);

		page = (page == null || page < 1) ? 1 : page;

		Pageable<Map<String, Object>> pagelist = qrcodeService.queryQrcodeBindingByID(userSession.getCompanyId(),
				paramMap, page);

		pagelist.setRquesturl(request, paramMap);

		model.put("pagelist", pagelist);

		for (String key : paramMap.keySet()) {
			model.put(key, paramMap.get(key));
		}

		return new ModelAndView("qrcode_binding_show").addAllObjects(model);
	}

	@ResponseBody
	@PostMapping("/qrcode/add")
	public HttpResponseBodyWrapper qrcode_add_post(HttpServletRequest request, String qcname, Byte type, Integer nubs)
			throws Exception {
		UserSession userSession = getUserSession(request);

		if (qcname == null || "".equals(qcname.trim())) {
			throw new BizzException(BizzException.error_code_invalid_params, "请输入二维码批次");
		}
		if (type == null || type < 0) {
			throw new BizzException(BizzException.error_code_invalid_params, "请输入二维码类型");
		}
		if (nubs == null || nubs <= 0 || nubs > 1000000) {
			throw new BizzException(BizzException.error_code_invalid_params, "请输入生成数量,或数量大于100万");
		}

		Integer result = qrcodeService.insertQrcode(qcname, type, nubs, userSession);
		if(-1==result){
			throw new BizzException(BizzException.error_code_invalid_params, "二维码批次不能重复！");
		}
		return new HttpResponseBodyWrapper(result);
	}

	@GetMapping("/qrcodegroup")
	public ModelAndView qrcode_group_list(HttpServletRequest request, String keyword, Integer state, Integer page)
			throws Exception {
		Map<String, Object> model = new HashMap<String, Object>();
		UserSession userSession = getUserSession(request);

		Map<String, Object> paramMap = getSimpleRequestParamMap(request);

		page = (page == null || page < 1) ? 1 : page;
		Pageable<Map<String, Object>> pagelist = qrcodeService
				.queryAllQrcodeGroupByCompnayID(userSession.getCompanyId(), paramMap, page);

		pagelist.setRquesturl(request, paramMap);

		model.put("pagelist", pagelist);
		
		
		//pbcId=8
		List<Pbc> listpbc = pbcService.queryPbc(userSession.getCompanyId(), 1);
		
		model.put("listpbc", listpbc);

		for (String key : paramMap.keySet()) {
			model.put(key, paramMap.get(key));
		}

		return new ModelAndView("qrcode_list_group").addAllObjects(model);
	}

	@GetMapping("/qrcodegroup/detail")
	public ModelAndView qrcode_group_detail_list(HttpServletRequest request,String  id,String proName, String qrId, Integer state, Integer page) throws Exception {
		Map<String, Object> model = new HashMap<String, Object>();
		UserSession userSession = getUserSession(request);

		Map<String, Object> paramMap = getSimpleRequestParamMap(request);

		page = (page == null || page < 1) ? 1 : page;

		Pageable<Map<String, Object>> pagelist = qrcodeService.queryQrcodegroupDetailByID(userSession.getCompanyId(),
				id,proName,qrId,state, page);

		if (null != pagelist && pagelist.getResult().size() > 0) {
			for (int j = 0; j < pagelist.getResult().size(); j++) {
				Map<String, Object> tmap = pagelist.getResult().get(j);
				if(tmap.get("w_uuid")!=null&&tmap.get("w_uuid").toString().length()>0){
					tmap.put("show_code",tmap.get("w_uuid").toString());
				}else{
					tmap.put("show_code", NumberConvetUtil.baseString(NumberUtils.toLong(tmap.get("id").toString(), 0L),
							NumberConvetUtil.SIXTY_CONVET));
				}
			}

		}

		pagelist.setRquesturl(request, paramMap);

		model.put("pagelist", pagelist);
		model.put("id", id);
		model.put("proName", proName);
		model.put("qrId", qrId);
		model.put("state", state);



		return new ModelAndView("qrcode_group_detail_list").addAllObjects(model);
	}

	@GetMapping("/qrcodegroup/binding")
	public ModelAndView qrcode_group_binding_show(HttpServletRequest request, Integer page) throws Exception {
		Map<String, Object> model = new HashMap<String, Object>();
		UserSession userSession = getUserSession(request);

		Map<String, Object> paramMap = getSimpleRequestParamMap(request);

		page = (page == null || page < 1) ? 1 : page;

		Pageable<Map<String, Object>> pagelist = qrcodeService.queryQrcodegroupBindingByID(userSession.getCompanyId(),
				paramMap, page);

		pagelist.setRquesturl(request, paramMap);

		model.put("pagelist", pagelist);

		for (String key : paramMap.keySet()) {
			model.put(key, paramMap.get(key));
		}

		return new ModelAndView("qrcode_group_binding_show").addAllObjects(model);
	}

	@ResponseBody
	@PostMapping("/qrcodegroup/add")
	public HttpResponseBodyWrapper qrcode_group_add_post(HttpServletRequest request, String qcname, Integer pbcId,
			Integer nubs) throws Exception {
		UserSession userSession = getUserSession(request);

		if (qcname == null || "".equals(qcname.trim())) {
			throw new BizzException(BizzException.error_code_invalid_params, "请输入二维码批次");
		}
		if (pbcId == null || pbcId <= 0) {
			throw new BizzException(BizzException.error_code_invalid_params, "请选择规格");
		}
		if (nubs == null || nubs <= 0 || nubs > 100000) {
			throw new BizzException(BizzException.error_code_invalid_params, "请输入生成数量或数量大于10万");
		}

		Integer result = qrcodeService.insertQrcodeGroup(qcname, pbcId, nubs, userSession);
		
		if(-1==result){
			throw new BizzException(BizzException.error_code_invalid_params, "二维码批次不能重复！");
		}
		
		return new HttpResponseBodyWrapper(result);
	}

	@GetMapping("/qrcodeproduct")
	public ModelAndView qrcode_product_list(HttpServletRequest request, Integer page) throws Exception {
		Map<String, Object> model = new HashMap<String, Object>();
		UserSession userSession = getUserSession(request);

		Map<String, Object> paramMap = getSimpleRequestParamMap(request);

		page = (page == null || page < 1) ? 1 : page;
		Pageable<Map<String, Object>> pagelist = qrcodeService
				.queryAllQrcodeProdcutCompnayID(userSession.getCompanyId(), paramMap, page);

		pagelist.setRquesturl(request, paramMap);

		model.put("pagelist", pagelist);

		//判断是否有启用营销权限
		Integer isStartMarket = 0;
		String resIds = userSession.getResIds();
		String[] res=resIds.split(",");
		List<String> resIdList = new ArrayList<String>();
		resIdList= Arrays.asList(res);
		if(resIdList.contains("320")==true)
		{
			isStartMarket=1;
		}
		model.put("isStartMarket", isStartMarket);

		for (String key : paramMap.keySet()) {
			model.put(key, paramMap.get(key));
		}

		return new ModelAndView("qrcode_product").addAllObjects(model);
	}
	/**
	 * 二维码绑定数据导出
	 * */
	@GetMapping("/qrcodeproduct/export")
    public String qrcode_product_export(HttpServletRequest request,HttpServletResponse response,String pname,
    		String qcname,String sta) throws IOException{
    	
    	UserSession userSession = getUserSession(request);
    	Map<String, Object> paramMap = new HashMap<String, Object>();
    	if(StringUtils.isNotBlank(pname)){
    		//商品名称
    		paramMap.put("pname", pname);
    	}
    	if(StringUtils.isNotBlank(qcname)){
    		//二维码名称
    		paramMap.put("qcname", qcname);
    	}
    	if(StringUtils.isNotBlank(sta)){
    		//状态，0解绑，1正常
    		paramMap.put("sta", sta);
    	}
    	
		List<Map<String, Object>> exportList = qrcodeService.queryAllQrcodeProdcutCompnayIDForExport(userSession.getCompanyId(), paramMap);
		
    	String fileName="二维码绑定数据导出"+DateUtils.dateToString(Calendar.getInstance().getTime(), "yyyy-MM-dd");
    	
    	List<Map<String,Object>> list= new ArrayList<Map<String,Object>>(exportList.size());
    	
    	Map<String,Object> fmap = null;
    	for(Map<String,Object> map : exportList){
    		fmap=new HashMap<String, Object>();
    		Long tid = NumberUtils.toLong(map.get("id").toString(), 0L);
    		//byte type = NumberUtils.toByte(map.get("type").toString(),(byte) 0);
    		fmap.put("id", tid);
    		fmap.put("pname", map.get("pname"));
    		fmap.put("qcname", map.get("qcname"));
    		
    		if((long)map.get("g_s_no") != 0){
    			fmap.put("g_s_no", map.get("g_s_no")+"\n"+map.get("s_no"));
    		}else{
    			fmap.put("g_s_no", map.get("s_no"));
    		}
    		if((long)map.get("g_e_no") != 0){
    			fmap.put("g_e_no", map.get("g_e_no") +"\n"+map.get("e_no"));
    		}else{
    			fmap.put("g_e_no", map.get("e_no"));
    		}
    		if((int)map.get("g_q_count") != 0){
    			fmap.put("g_q_count", map.get("g_q_count")+"\n"+map.get("q_count"));
    		}else{
    			fmap.put("g_q_count", map.get("q_count"));
    		}
    		
    		
    		if((int)map.get("g_q_count") == 0){
    			if((int)map.get("type") == 1){
    				fmap.put("type", "瓶码/盒码");
    			}else if((int)map.get("type") == 2){
    				fmap.put("type", "箱码");
    			}
    		}else{
    			if((int)map.get("type") == 3){
    				fmap.put("type", "箱码(组合码)\n瓶码/盒码(组合码)");
    			}
    		}
    		
    		if((boolean)map.get("sta")){
    			fmap.put("sta", "已绑定");
    		}else{
    			fmap.put("sta", "解绑");
    		}
    		
    		
    		String time = DateUtils.formatTimeInMillis((Long)map.get("c_time"));
    		fmap.put("c_time", time);
    		
    		fmap.put("c_admin", map.get("c_admin"));
    		
    		
    		list.add(fmap);
    	}
    	
    	
    	
    	String columnNames[] = {"ID","绑定产品","二维码批次","开始编号","结束编号","绑定数量","类型","状态","生成时间","操作人"};//列名
    	String keys[] = {"id","pname","qcname","g_s_no","g_e_no","g_q_count","type","sta","c_time","c_admin"};//map中的key
    	ByteArrayOutputStream os = new ByteArrayOutputStream();
    	try {
    		ExcelUtil.createWorkBook(list,keys,columnNames).write(os);
    	} catch (IOException e) {
    		e.printStackTrace();
    	}
    	byte[] content = os.toByteArray();
    	InputStream is = new ByteArrayInputStream(content);
    	// 设置response参数，可以打开下载页面
    	response.reset();
    	response.setContentType("application/vnd.ms-excel;charset=utf-8");
    	response.setHeader("Content-Disposition", "attachment;filename="+ new String((fileName + ".xls").getBytes(), "iso-8859-1"));
    	ServletOutputStream out = response.getOutputStream();
    	BufferedInputStream bis = null;
    	BufferedOutputStream bos = null;
    	try {
    		bis = new BufferedInputStream(is);
    		bos = new BufferedOutputStream(out);
    		byte[] buff = new byte[2048];
    		int bytesRead;
    		// Simple read/write loop.
    		while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
    			bos.write(buff, 0, bytesRead);
    			bos.flush();
    		}
    	} catch (final IOException e) {
    		throw e;
    	} finally {
    		if (bis != null)
    			bis.close();
    		if (bos != null)
    			bos.close();
    	}
    	
    	return null;
    }

	@ResponseBody
	@GetMapping("/querypname")
	public List<Map<String, Object>> query_pname(HttpServletRequest request, String pname, Integer limit)
			throws Exception {
		UserSession userSession = getUserSession(request);

		if (pname == null || "".equals(pname.trim())) {
			return null;
		}
		if (limit == null || limit <= 0 || limit > 30) {
			limit = 8;
		}

		List<Map<String, Object>> prolist = qrcodeService.queryProductName(pname.trim(), limit,
				userSession.getCompanyId());

		return prolist;
	}

	@ResponseBody
	@GetMapping("/queryqcname")
	public List<Map<String, Object>> query_qcname(HttpServletRequest request, String qcname, Integer type, Integer limit)
			throws Exception {
		UserSession userSession = getUserSession(request);

		if (qcname == null || "".equals(qcname.trim())) {
			return null;
		}
		if (limit == null || limit <= 0 || limit > 30) {
			limit = 8;
		}

		List<Map<String, Object>> prolist = qrcodeService.queryQrcodeName(qcname.trim(), type, limit,
				userSession.getCompanyId());

		return prolist;
	}

	@ResponseBody
	@GetMapping("/qrcode/count")
	public HttpResponseBodyWrapper qrcode_count(HttpServletRequest request, Integer id, Integer type) throws Exception {

		if (id == null || id <= 0) {
			return new HttpResponseBodyWrapper(new HashMap<String, Object>());
		}

		UserSession userSession = getUserSession(request);
		
		Integer companyid = userSession.getCompanyId();
		
		Map<String, Object> map = qrcodeService.queryQrcodeNoBangdingCount(id, type,companyid);
		return new HttpResponseBodyWrapper(map);
	}
	
	@ResponseBody
	@GetMapping("/qrcodeproduct/qrcodepbc")
	public HttpResponseBodyWrapper queryQrcodePbcchangproduct(HttpServletRequest request, Integer id) throws Exception {

		if (id == null || id <= 0) {
			return new HttpResponseBodyWrapper(new HashMap<String, Object>());
		}
		
		Map<String, Object> map = qrcodeService.queryQrcodePbcchangproduct(id);
//		System.out.println(map);
		return new HttpResponseBodyWrapper(map);
	}

	@ResponseBody
	@PostMapping("/qrcodeproduct/add")
	public HttpResponseBodyWrapper qrcode_product_add_post(HttpServletRequest request) throws Exception {

		Map<String, Object> paramMap = getSimpleRequestParamMap(request);

		Integer type = 0;

		if (!paramMap.containsKey("pname") || (-1 == paramMap.get("pname").toString().indexOf("_"))) {
			throw new BizzException(BizzException.error_code_invalid_params, "产品名称选择有误！");
		}
		if(!paramMap.containsKey("batch_nub")){
			throw new BizzException(BizzException.error_code_invalid_params, "批次号有误！");
		}else{
			String batch_nub = (String)paramMap.get("batch_nub");
			if(!Pattern.matches(ValidUtil.PWS_PATTERN,batch_nub)){
				throw new BizzException(BizzException.error_code_invalid_params, "请输入数字、字母组成的批次号！");
			}
		}

		if (!paramMap.containsKey("qcname") || (-1 == paramMap.get("qcname").toString().indexOf("_"))) {
			throw new BizzException(BizzException.error_code_invalid_params, "二维码批次选择有误！");
		}

		if (!paramMap.containsKey("type")) {
			throw new BizzException(BizzException.error_code_invalid_params, "二维码类型选择有误！");
		} else {
			type = NumberUtils.toInt(paramMap.get("type").toString(), -1);
			if (type > 3 || type < 1) {
				throw new BizzException(BizzException.error_code_invalid_params, "二维码类型选择有误！");
			}

		}
		if (!paramMap.containsKey("pms") || !paramMap.containsKey("pme")) {
			throw new BizzException(BizzException.error_code_invalid_params, "瓶码开始结束编号有误！");
		}
		if (type == 3 && (!paramMap.containsKey("xms") || !paramMap.containsKey("xme"))) {
			throw new BizzException(BizzException.error_code_invalid_params, "箱码开始结束编号有误！");
		}

		UserSession userSession = getUserSession(request);

		Integer result = qrcodeService.insertQrcodeProduct(paramMap, type, userSession);
		
		
		if(-1==result){
			throw new BizzException(BizzException.error_code_invalid_params, "商品id有误！");
		}else if(-2==result){
			throw new BizzException(BizzException.error_code_invalid_params, "需要绑定的二维码的id有误！");
		}else if(-3==result){
			throw new BizzException(BizzException.error_code_invalid_params, "二维码的编号范围不正确！");
		}else if(-4==result){
			throw new BizzException(BizzException.error_code_invalid_params, "组合码的瓶码编号不正确！");
		}else if(-5==result){
			throw new BizzException(BizzException.error_code_invalid_params, "此号段已被其他人绑定，请刷新列表，重新绑定！");
		}
		
		
		return new HttpResponseBodyWrapper(result);
	}

	@ResponseBody
	@PostMapping("/qrcodeproduct/edit")
	public HttpResponseBodyWrapper qrcode_product_edit_post(HttpServletRequest request, String pname,String batch_nub, Integer id,
			Integer type,Integer pid,String produce_date) throws Exception {
		UserSession userSession = getUserSession(request);

		if (pname == null || "".equals(pname.trim()) || (-1 == pname.indexOf("_"))) {
			throw new BizzException(BizzException.error_code_invalid_params, "产品名称选择有误！");
		}
		if (id == null || id <= 0) {
			throw new BizzException(BizzException.error_code_invalid_params, "绑定id不正确");
		}
		if(batch_nub == null || batch_nub.equals("")){
			throw new BizzException(BizzException.error_code_invalid_params, "批次号有误！");
		}else{
			if(!Pattern.matches(ValidUtil.PWS_PATTERN,batch_nub)){
				throw new BizzException(BizzException.error_code_invalid_params, "请输入数字、字母组成的批次号！");
			}
		}

		if (null == type || (type > 3 || type < 1)) {
			throw new BizzException(BizzException.error_code_invalid_params, "二维码类型选择有误！");
		}

		Integer result = qrcodeService.updateQrcodeGroup(id, pname,batch_nub, type,pid,produce_date, userSession);
		return new HttpResponseBodyWrapper(result);
	}

	@ResponseBody
	@GetMapping("/qrcodeprocut/resetendnobyxme")
	public Long qrcode_procut_resetendbhbyxme(HttpServletRequest request, Integer id) throws Exception {

		if (id == null || id <= 0) {
			return 0L;
		}

		UserSession userSession = getUserSession(request);
		
		Long rn = qrcodeService.queryQrcodeProductResetEndNoByXme(id,userSession.getCompanyId());

		return rn;
	}

	@ResponseBody
	@PostMapping("/qrcodeproduct/delete")
	public HttpResponseBodyWrapper qrcode_product_delete_post(HttpServletRequest request, Integer id, Integer type)
			throws Exception {

		if (id <= 0) {
			throw new BizzException(BizzException.error_code_invalid_params, "绑定id有误！");
		}

		if (type > 3 || type < 1) {
			throw new BizzException(BizzException.error_code_invalid_params, "二维码类型有误！");
		}

		UserSession userSession = getUserSession(request);

		Integer result = qrcodeService.deleteQrcodeProduct(id, userSession, type);
		return new HttpResponseBodyWrapper(result);
	}
	
	@ResponseBody
	@PostMapping("/qrcodeproduct/upact")
	public HttpResponseBodyWrapper qrcode_product_upact_post(HttpServletRequest request, Integer id, Integer type)
			throws Exception {

		if (id <= 0) {
			throw new BizzException(BizzException.error_code_invalid_params, "绑定id有误！");
		}

		if (type != 0 && type != 1) {
			throw new BizzException(BizzException.error_code_invalid_params, "营销状态有误！");
		}

		UserSession userSession = getUserSession(request);

		Integer result = qrcodeService.updateQrcodeProductActSta(id, userSession, type);
		return new HttpResponseBodyWrapper(result);
	}
	/**
	 * 普通二维码下载
	 * @author kelan
	 * @date 2017年10月25日
	 * @param request
	 * @param response
	 * @param id
	 * @param qcname
	 * @param isAutoDraw
	 * @return
	 * @throws IOException
	 */
	@GetMapping("/qrcode/download")
	public String qrcode_download(HttpServletRequest request, HttpServletResponse response, Integer id, String qcname,Integer isAutoDraw)
			throws IOException {
		UserSession userSession = getUserSession(request);
		if (null == id || id <= 0) {
			throw new BizzException(BizzException.error_code_invalid_params, "二维码id错误！");
		}
		if (null == qcname) {
			throw new BizzException(BizzException.error_code_invalid_params, "二维码批次错误！");
		}
		String fileName = "普通二维码《" + qcname + "》明细下载";
		if(isAutoDraw==1){
			fileName = "普通二维码《" + qcname + "》明细下载(营销码)";
		}else if(isAutoDraw==0){
			fileName = "普通二维码《" + qcname + "》明细下载(物流码)";
		}
		Integer companyid = userSession.getCompanyId();
		String tmpfilefullname = picStoragePath + "/downloadfile/"+companyid+"_"+id+"_"+fileName + ".txt";
		File temf = new File(tmpfilefullname);
		if (temf.exists()){
			temf.delete();
		}
		if (!temf.exists()) {
			if (!temf.getParentFile().exists()) {
				temf.getParentFile().mkdirs();
			}
			temf.createNewFile();
			List<Map<String, Object>> qrcodelist = qrcodeService.queryQrcodeInfoForDownload(id, isAutoDraw ,userSession);
			FileWriter fw = null;
			BufferedWriter writer = null;
			try {
				fw = new FileWriter(tmpfilefullname);
				writer = new BufferedWriter(fw);
				String sb = null;
				// 0000000001，http://scan.vats.com.cn/s/2/a1ff8a3321f94986b432384a3da4b9fc
				for (Map<String, Object> map : qrcodelist) {
					Long tid = NumberUtils.toLong(map.get("id").toString(), 0L);
					sb = String.valueOf(tid);
					int length = sb.length();
					for (int a = 11; a > length; a--) {
						sb = "0" + sb;
					}
					//其中 2：代表历史普通码瓶码 （营销码）；3：代表历史普通码箱码 （物流码） ；
					//4：组合码瓶码 物流码 ；5：代表组合码箱码（物流码）；6：代表普通码（营销码）7.普通码（物流码）
					Byte qrtype = NumberUtils.toByte(map.get("type").toString(), (byte) 1);
					if(isAutoDraw==1){
						writer.write(sb + "," + qrcode_valid_url + 6+ "/" + map.get("uuid").toString());
						//writer.write("\r\n");// 换行
						//writer.write(sb + "," + qrcode_valid_url + 7 + "/" + map.get("w_uuid").toString());
					}else if(isAutoDraw==0) {
						writer.write(sb + "," + qrcode_valid_url + 7+ "/" + map.get("w_uuid").toString());
					}else if(isAutoDraw==3) {
						writer.write(sb + "," + qrcode_valid_url + (qrtype+1) + "/" + map.get("w_uuid").toString());
					}else{
						writer.write(sb + "," + qrcode_valid_url + (qrtype+1) + "/" + map.get("uuid").toString());
					}
					writer.write("\r\n");// 换行
				}
				//writer.newLine();
				writer.flush();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					writer.close();
					fw.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

		}

		InputStream is = new FileInputStream(tmpfilefullname);
		// OutputStream out = response.getOutputStream();

		// 更新下载状态
		qrcodeService.updateDownlaodState(id);

		// ByteArrayOutputStream os = new ByteArrayOutputStream();
		// byte[] content = os.toByteArray();
		// InputStream is = new ByteArrayInputStream(content);
		// 设置response参数，可以打开下载页面
		response.reset();
		response.setContentType("application/vnd.ms-excel;charset=utf-8");
		response.setHeader("Content-Disposition",
				"attachment;filename=" + new String((fileName + ".txt").getBytes(), "iso-8859-1"));
		ServletOutputStream out = response.getOutputStream();
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			bis = new BufferedInputStream(is);
			bos = new BufferedOutputStream(out);
			byte[] buff = new byte[2048];
			int bytesRead;
			// Simple read/write loop.
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
				bos.flush();
			}
		} catch (final IOException e) {
			throw e;
		} finally {
			if (bis != null)
				bis.close();
			if (bos != null)
				bos.close();
		}

		return null;
	}
	/**
	 * 短地址下载
	 * @author kelan
	 * @date 2017年10月25日
	 * @param request
	 * @param response
	 * @param id
	 * @param qcname
	 * @param isAutoDraw
	 * @return
	 * @throws IOException
	 */
	@GetMapping("/qrshortcode/download")
	public String qrshortcode_download(HttpServletRequest request, HttpServletResponse response, Integer id, String qcname,Integer isAutoDraw)
			throws IOException {
		UserSession userSession = getUserSession(request);
		if (null == id || id <= 0) {
			throw new BizzException(BizzException.error_code_invalid_params, "二维码id错误！");
		}
		if (null == qcname) {
			throw new BizzException(BizzException.error_code_invalid_params, "二维码批次错误！");
		}
		String fileName = "普通二维码《" + qcname + "》短地址明细下载";
		Integer companyid = userSession.getCompanyId();
		String tmpfilefullname = picStoragePath + "/downloadfile/"+companyid+"_"+id+"_"+fileName + ".txt";
		File temf = new File(tmpfilefullname);
		if (temf.exists()){
			temf.delete();
		}
		if (!temf.exists()) {
			if (!temf.getParentFile().exists()) {
				temf.getParentFile().mkdirs();
			}
			temf.createNewFile();
			List<Map<String, Object>> qrcodelist = qrcodeService.queryQrcodeInfoForDownload(id, isAutoDraw ,userSession);
			FileWriter fw = null;
			BufferedWriter writer = null;
			try {
				fw = new FileWriter(tmpfilefullname);
				writer = new BufferedWriter(fw);
				String[] sbs = new String[qrcodelist.size()];
				int len = (int) (qrcodelist.size()%batchNumber==0?qrcodelist.size()/batchNumber:qrcodelist.size()/batchNumber+1);
				String[] shorturl = new String[0];
				String[] w_shorturl = new String[0];
				if(qrcodelist.size() <= batchNumber){
					StringBuilder longurl = new StringBuilder();//新建营销字符串一个对象  
					StringBuilder w_longurl = new StringBuilder();//新建物流字符一个对象 
					//二维码长地址生成规则
	        		Map<String,Object> retmap = Handle_qrcode(isAutoDraw, qrcodelist);
	        		sbs = (String[]) retmap.get("sbs");
	        		longurl = (StringBuilder) retmap.get("longurl");
	        		w_longurl = (StringBuilder) retmap.get("w_longurl");
					if(isAutoDraw==3){
						//请求接口获取短地址
		        		Map<String,Object> reqmap =  Request_shorturl(isAutoDraw, longurl, w_longurl, shorturl, w_shorturl);
		        		shorturl = (String[]) reqmap.get("shorturl");
					}else{
						//请求接口获取短地址
		        		Map<String,Object> reqmap =  Request_shorturl(isAutoDraw, longurl, w_longurl, shorturl, w_shorturl);
		        		shorturl = (String[]) reqmap.get("shorturl");
		        		w_shorturl = (String[]) reqmap.get("w_shorturl");
					}
				}else{
					String[] sbs1 = new String[0];
					for(int k = 0 ;k < len ; k++){
						//新建营销字符串一个对象 
						StringBuilder longurl = new StringBuilder(); 
						//新建物流字符一个对象 
						StringBuilder w_longurl = new StringBuilder();
		        		List<Map<String, Object>> templist = new ArrayList<Map<String, Object>>();
		        		templist.addAll(qrcodelist);
		        		Integer fromIndex = (int) (batchNumber*k);
		        		Integer toIndex = (int) ((batchNumber*k)+batchNumber);
		        		if(k == len-1){
		        			toIndex = (int) ((batchNumber*k)+((qrcodelist.size()%batchNumber==0?batchNumber:qrcodelist.size()%batchNumber)));
		        		}
		        		templist = templist.subList(fromIndex, toIndex);
		        		//二维码长地址生成规则
		        		Map<String,Object> retmap = Handle_qrcode(isAutoDraw, templist);
		        		String[] sbs2 = (String[]) retmap.get("sbs");
		        		int strLen1 = sbs1.length;// 保存第一个数组长度
		    	        int strLen2 = sbs2.length;// 保存第二个数组长度
		    	        sbs1 = Arrays.copyOf(sbs1, strLen1 + strLen2);// 扩容
		    	        System.arraycopy(sbs2, 0, sbs1, strLen1, strLen2);// 将第二个数组与第一个数组合并
		        		longurl = (StringBuilder) retmap.get("longurl");
		        		w_longurl = (StringBuilder) retmap.get("w_longurl");
						if(isAutoDraw==3){
							//请求接口获取短地址
			        		Map<String,Object> reqmap =  Request_shorturl(isAutoDraw, longurl, w_longurl, shorturl, w_shorturl);
			        		shorturl = (String[]) reqmap.get("shorturl");
						}else{
							//请求接口获取短地址
			        		Map<String,Object> reqmap =  Request_shorturl(isAutoDraw, longurl, w_longurl, shorturl, w_shorturl);
			        		shorturl = (String[]) reqmap.get("shorturl");
			        		w_shorturl = (String[]) reqmap.get("w_shorturl");
						}
		    		}
					sbs = sbs1;
				}
				if(isAutoDraw==3){
					int j =0; 
					for(String tempurl :shorturl){
						writer.write(sbs[j]+","+tempurl);
						j++;
						writer.write("\r\n");// 换行
					}
					writer.flush();
				}else{
					int j =0;
					for(String w_tempurl :w_shorturl){
						for(int kk = 0 ; kk< shorturl.length ; kk++ ){
							if(j == kk){
								writer.write(sbs[j]+","+w_tempurl+","+shorturl[kk]);
								continue;
							}
						}
						j++;
						writer.write("\r\n");// 换行
					}
					writer.flush();
				}
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					writer.close();
					fw.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

		}

		InputStream is = new FileInputStream(tmpfilefullname);
		// OutputStream out = response.getOutputStream();

		// 更新下载状态
		qrcodeService.updateDownlaodState(id);
		// ByteArrayOutputStream os = new ByteArrayOutputStream();
		// byte[] content = os.toByteArray();
		// InputStream is = new ByteArrayInputStream(content);
		// 设置response参数，可以打开下载页面
		response.reset();
		response.setContentType("application/vnd.ms-excel;charset=utf-8");
		response.setHeader("Content-Disposition",
				"attachment;filename=" + new String((fileName + ".txt").getBytes(), "iso-8859-1"));
		ServletOutputStream out = response.getOutputStream();
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			bis = new BufferedInputStream(is);
			bos = new BufferedOutputStream(out);
			byte[] buff = new byte[2048];
			int bytesRead;
			// Simple read/write loop.
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
				bos.flush();
			}
		} catch (final IOException e) {
			throw e;
		} finally {
			if (bis != null)
				bis.close();
			if (bos != null)
				bos.close();
		}

		return null;
	}
	
	
	/**
	 * 普通二维码 长地址 生成规则
	 * @author kelan
	 * @date 2018年2月1日
	 * @param isAutoDraw
	 * @param qrcodelist
	 * @return
	 */
	public Map<String,Object> Handle_qrcode(Integer isAutoDraw ,List<Map<String,Object>> qrcodelist){
		Map<String,Object> retmap = new HashMap<String,Object>();
		String sb = null;
		String[] sbs = new String[qrcodelist.size()];
		int i = 0 ;
		StringBuilder longurl = new StringBuilder();//新建营销字符串一个对象  
		StringBuilder w_longurl = new StringBuilder();//新建物流字符一个对象 
		for (Map<String, Object> map : qrcodelist) {
			Long tid = NumberUtils.toLong(map.get("id").toString(), 0L);
			sb = String.valueOf(tid);
			int length = sb.length();
			for (int a = 11; a > length; a--) {
				sb = "0" + sb;
			}
			sbs[i]=sb;
			i++;
			//其中 2：代表历史普通码瓶码 （营销码）；3：代表历史普通码箱码 （物流码） ；
			//4：组合码瓶码 物流码 ；5：代表组合码箱码（物流码）；6：代表普通码（营销码）7.普通码（物流码）
			Byte qrtype = NumberUtils.toByte(map.get("type").toString(), (byte) 1);
			if(isAutoDraw==3) {
				if(longurl.length()<=0){
					longurl.append(qrcode_valid_url + (qrtype+1) + "/" + map.get("w_uuid").toString());
				}else{
					longurl.append(","+ qrcode_valid_url + (qrtype+1) + "/" + map.get("w_uuid").toString());
				}
			}else if(isAutoDraw==4) {
				if(longurl.length()<=0){
					longurl.append(qrcode_valid_url + 6+ "/" + map.get("uuid").toString());
				}else{
					longurl.append(","+ qrcode_valid_url + 6+ "/" + map.get("uuid").toString());
				}
				if(w_longurl.length()<=0){
					w_longurl.append(qrcode_valid_url + 7+ "/" + map.get("w_uuid").toString());
				}else{
					w_longurl.append(","+ qrcode_valid_url + 7+ "/" + map.get("w_uuid").toString());
				}
			}else{
				if(longurl.length()<=0){
					longurl.append(qrcode_valid_url + (qrtype+1) + "/" + map.get("uuid").toString());
				}else{
					longurl.append(","+ qrcode_valid_url + (qrtype+1) + "/" + map.get("uuid").toString());
				}
			}
		}
		retmap.put("sbs", sbs);
		retmap.put("longurl", longurl);
		retmap.put("w_longurl", w_longurl);
		return retmap;
	}
	
	/**
	 * 请求接口，返回短地址数组
	 * @author kelan
	 * @date 2018年2月1日
	 * @param isAutoDraw
	 * @param longurl
	 * @param w_longurl
	 * @param shorturl
	 * @param w_shorturl
	 * @return
	 */
	public Map<String,Object> Request_shorturl (Integer isAutoDraw,StringBuilder longurl,StringBuilder w_longurl,String[] shorturl,String[] w_shorturl ){
		Map<String,Object> retmap = new HashMap<String,Object>();
		if(isAutoDraw==3){
			String url = dApisurl+"?token="+dApistoken;
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("url", longurl);
			map.put("prefix", "E");
			String result = HttpClientUtil.HttpPostWithMap(url, map);
			String[] reshorturl=new String[0];
			if(result.indexOf("{")>=0&&result.indexOf("}")>=0){
				JSONObject js = JSONObject.parseObject(result);
				if(js.containsKey("code") && js.getInteger("code")==200){
					reshorturl = js.get("data").toString().replace("[", "").replace("]", "").replace("\"", "").split(",");
				}
			}
			int strLen1 = shorturl.length;// 保存第一个数组长度
	        int strLen2 = reshorturl.length;// 保存第二个数组长度
	        shorturl = Arrays.copyOf(shorturl, strLen1 + strLen2);// 扩容
	        System.arraycopy(reshorturl, 0, shorturl, strLen1, strLen2);// 将第二个数组与第一个数组合并
	        retmap.put("shorturl", shorturl);
		}else{
			String url = dApisurl+"?token="+dApistoken;
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("url", longurl);
			map.put("prefix", "B");
			String result = HttpClientUtil.HttpPostWithMap(url, map);
			String[] reshorturl=new String[0];
			if(result.indexOf("{")>=0&&result.indexOf("}")>=0){
				JSONObject js = JSONObject.parseObject(result);
				if(js.containsKey("code") && js.getInteger("code")==200){
					reshorturl = js.get("data").toString().replace("[", "").replace("]", "").replace("\"", "").split(",");
				}
			}
			int strLen1 = shorturl.length;// 保存第一个数组长度
	        int strLen2 = reshorturl.length;// 保存第二个数组长度
	        shorturl = Arrays.copyOf(shorturl, strLen1 + strLen2);// 扩容
	        System.arraycopy(reshorturl, 0, shorturl, strLen1, strLen2);// 将第二个数组与第一个数组合并
//			System.out.println(shorturl);
			String w_url = dApisurl+"?token="+dApistoken;
			Map<String, Object> w_map = new HashMap<String, Object>();
			w_map.put("url", w_longurl);
			w_map.put("prefix", "A");
			String w_result = HttpClientUtil.HttpPostWithMap(w_url, w_map);
			String[] w_reshorturl=new String[0];
			if(result.indexOf("{")>=0&&result.indexOf("}")>=0){
				JSONObject js = JSONObject.parseObject(w_result);
				if(js.containsKey("code") && js.getInteger("code")==200){
					w_reshorturl = js.get("data").toString().replace("[", "").replace("]", "").replace("\"", "").split(",");
				}
			}
			int w_strLen1 = w_shorturl.length;// 保存第一个数组长度
	        int w_strLen2 = w_reshorturl.length;// 保存第二个数组长度
	        w_shorturl = Arrays.copyOf(w_shorturl, w_strLen1 + w_strLen2);// 扩容
	        System.arraycopy(w_reshorturl, 0, w_shorturl, w_strLen1, w_strLen2);// 将第二个数组与第一个数组合并
			retmap.put("shorturl", shorturl);
			retmap.put("w_shorturl", w_shorturl);
		}
		return retmap;
	}
	/**
	 * 二维码数据导出
	 * */
	@GetMapping("/qrcode/export")
    public String qrcode_export(HttpServletRequest request,HttpServletResponse response,Integer page,String qcname,
    		String state,String isprint,Integer tsno,Integer teno,
    		Integer ysno,Integer yeno) throws IOException{
    	
    	UserSession userSession = getUserSession(request);
    	Map<String, Object> paramMap = new HashMap<String, Object>();
    	if(StringUtils.isNotBlank(qcname)){
    		paramMap.put("qcname", qcname);
    	}
    	if(StringUtils.isNotBlank(state)){
    		paramMap.put("state", state);
    	}
    	if(StringUtils.isNotBlank(isprint)){
    		paramMap.put("isprint", isprint);
    	}
    	if(tsno != null){
    		paramMap.put("tsno", tsno);
    	}
    	if(teno != null){
    		paramMap.put("teno", teno);
    	}
    	if(ysno != null){
    		paramMap.put("ysno", ysno);
    	}
    	if(yeno != null){
    		paramMap.put("yeno", yeno);
    	}
    	
    	page = (page == null || page < 1) ? 1 : page;
        List<Map<String,Object>> exportList = qrcodeService.queryAllQrcodeByCompnayIDForExport(userSession.getCompanyId(), paramMap);
        	
    	String fileName="二维码数据导出"+DateUtils.dateToString(Calendar.getInstance().getTime(), "yyyy-MM-dd");
    	
    	List<Map<String,Object>> list= new ArrayList<Map<String,Object>>(exportList.size());
    	
    	Map<String,Object> fmap = null;
    	for(Map<String,Object> map : exportList){
    		fmap=new HashMap<String, Object>();
    		Long tid = NumberUtils.toLong(map.get("id").toString(), 0L);
    		byte type = NumberUtils.toByte(map.get("type").toString(),(byte) 0);
    		//byte isPring = NumberUtils.toByte(map.get("is_print").toString(),(byte) 0);
    		fmap.put("id", tid);
    		fmap.put("qcname", map.get("qcname"));
    		fmap.put("start_no", map.get("minid"));
    		fmap.put("end_no", map.get("maxid"));
    		fmap.put("type", 1==type?"瓶码/盒码":"箱码");
    		fmap.put("hava_no", map.get("total"));
    		fmap.put("bandings_nub", map.get("bd"));
    		fmap.put("scan_no", map.get("scan_nub"));
    		
    		String time = DateUtils.formatTimeInMillis((Long)map.get("c_time"));
    		fmap.put("c_time", time);
    		
    		fmap.put("c_admin", map.get("c_admin"));
    		if((boolean) map.get("is_print")){
    			fmap.put("is_print", "是");
    		}else{
    			fmap.put("is_print", "否");
    		}
    		
    		list.add(fmap);
    	}
    	
    	String columnNames[] = {"ID","二维码批次","开始编号","结束编号","类型","总数量","绑定量","已扫量","生成时间","操作人","是否打印"};//列名
    	String keys[] = {"id","qcname","start_no","end_no","type","hava_no","bandings_nub","scan_no","c_time","c_admin","is_print"};//map中的key
    	ByteArrayOutputStream os = new ByteArrayOutputStream();
    	try {
    		ExcelUtil.createWorkBook(list,keys,columnNames).write(os);
    	} catch (IOException e) {
    		e.printStackTrace();
    	}
    	byte[] content = os.toByteArray();
    	InputStream is = new ByteArrayInputStream(content);
    	// 设置response参数，可以打开下载页面
    	response.reset();
    	response.setContentType("application/vnd.ms-excel;charset=utf-8");
    	response.setHeader("Content-Disposition", "attachment;filename="+ new String((fileName + ".xls").getBytes(), "iso-8859-1"));
    	ServletOutputStream out = response.getOutputStream();
    	BufferedInputStream bis = null;
    	BufferedOutputStream bos = null;
    	try {
    		bis = new BufferedInputStream(is);
    		bos = new BufferedOutputStream(out);
    		byte[] buff = new byte[2048];
    		int bytesRead;
    		// Simple read/write loop.
    		while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
    			bos.write(buff, 0, bytesRead);
    			bos.flush();
    		}
    	} catch (final IOException e) {
    		throw e;
    	} finally {
    		if (bis != null)
    			bis.close();
    		if (bos != null)
    			bos.close();
    	}
    	
    	
        
    	return null;
    }

	/**
	 * 组合码导出
	 * */
	@GetMapping("/qrcodegroup/export")
    public String qrcode_group_export(HttpServletRequest request,HttpServletResponse response,Integer page,String qcname,
    		String pbcId,String isprint,Integer tsno,Integer teno,
    		Integer ysno,Integer yeno,Integer xsno,Integer xeno,Integer psno,Integer peno) throws IOException{
    	
    	UserSession userSession = getUserSession(request);
    	Map<String, Object> paramMap = new HashMap<String, Object>();
    	if(StringUtils.isNotBlank(qcname)){
    		paramMap.put("qcname", qcname);
    	}
    	if(StringUtils.isNotBlank(pbcId)){
    		paramMap.put("pbcId", pbcId);
    	}
    	if(StringUtils.isNotBlank(isprint)){
    		paramMap.put("isprint", isprint);
    	}
    	if(tsno != null){
    		paramMap.put("tsno", tsno);
    	}
    	if(teno != null){
    		paramMap.put("teno", teno);
    	}
    	if(ysno != null){
    		paramMap.put("ysno", ysno);
    	}
    	if(yeno != null){
    		paramMap.put("yeno", yeno);
    	}
    	if(xsno != null){
    		paramMap.put("xsno", xsno);
    	}
    	if(xeno != null){
    		paramMap.put("xeno", xeno);
    	}
    	if(psno != null){
    		paramMap.put("psno", psno);
    	}
    	if(xeno != null){
    		paramMap.put("peno", peno);
    	}
    	
    	List<Map<String, Object>> exportList = qrcodeService.queryAllQrcodeGroupByCompnayIDForExport(userSession.getCompanyId(), paramMap);
        	
    	String fileName="组合码数据导出"+DateUtils.dateToString(Calendar.getInstance().getTime(), "yyyy-MM-dd");
    	
    	List<Map<String,Object>> list= new ArrayList<Map<String,Object>>(exportList.size());
    	
    	Map<String,Object> fmap = null;
    	for(Map<String,Object> map : exportList){
    		fmap=new HashMap<String, Object>();
    		Long tid = NumberUtils.toLong(map.get("id").toString(), 0L);
    		fmap.put("id", tid);
    		fmap.put("qcname", map.get("qcname"));
    		fmap.put("pbc_id", "1*"+map.get("pbc_id"));
    		fmap.put("gminid", map.get("gminid")+"\r\n"+map.get("minid"));
    		fmap.put("gmaxid", map.get("gmaxid")+"\r\n"+map.get("maxid"));
    		fmap.put("type", "箱码\r\n瓶码/盒码");
    		fmap.put("gtotal", map.get("gtotal")+"\r\n"+map.get("total"));
    		fmap.put("gbd", map.get("gbd")+"\r\n"+map.get("bd"));
    		fmap.put("gscan_nub", map.get("gscan_nub")+"\r\n"+map.get("scan_nub"));
    		
    		String time = DateUtils.formatTimeInMillis((Long)map.get("c_time"));
    		fmap.put("c_time", time);
    		
    		fmap.put("c_admin", map.get("c_admin"));
    		if((boolean) map.get("is_print")){
    			fmap.put("is_print", "是");
    		}else{
    			fmap.put("is_print", "否");
    		}
    		
    		list.add(fmap);
    	}
    	
    	String columnNames[] = {"ID","组合码批次","二维码规格","开始编号","结束编号","类型","总数量","绑定量","已扫量","生成时间","操作人","是否打印"};//列名
    	String keys[] = {"id","qcname","pbc_id","gminid","gmaxid","type","gtotal","gbd","gscan_nub","c_time","c_admin","is_print"};//map中的key
    	ByteArrayOutputStream os = new ByteArrayOutputStream();
    	try {
    		ExcelUtil.createWorkBook(list,keys,columnNames).write(os);
    	} catch (IOException e) {
    		e.printStackTrace();
    	}
    	byte[] content = os.toByteArray();
    	InputStream is = new ByteArrayInputStream(content);
    	// 设置response参数，可以打开下载页面
    	response.reset();
    	response.setContentType("application/vnd.ms-excel;charset=utf-8");
    	response.setHeader("Content-Disposition", "attachment;filename="+ new String((fileName + ".xls").getBytes(), "iso-8859-1"));
    	ServletOutputStream out = response.getOutputStream();
    	BufferedInputStream bis = null;
    	BufferedOutputStream bos = null;
    	try {
    		bis = new BufferedInputStream(is);
    		bos = new BufferedOutputStream(out);
    		byte[] buff = new byte[2048];
    		int bytesRead;
    		// Simple read/write loop.
    		while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
    			bos.write(buff, 0, bytesRead);
    			bos.flush();
    		}
    	} catch (final IOException e) {
    		throw e;
    	} finally {
    		if (bis != null)
    			bis.close();
    		if (bos != null)
    			bos.close();
    	}
    	
    	
        
    	return null;
    }
	/**
	 * @author kelan
	 * @date 2017年3月9日
	 * @param request
	 * @param response
	 * @param id
	 * @param qcname
	 * http://scan.vats.com.cn/s/2/a1ff8a3321f94986b432384a3da4b9fc  其中 2：代表历史普通码瓶码 （营销码）；3：代表历史普通码箱码 （物流码） ；4：组合码瓶码 物流码 ；5：代表组合码箱码（物流码）；6：代表普通码（营销码）7.普通码（物流码）
	 * @return 
	 * @throws IOException
	 */
	@GetMapping("/qrcodegroup/download")
	public String qrcode_group_download(HttpServletRequest request, HttpServletResponse response, Integer id,
			String qcname) throws IOException {

		UserSession userSession = getUserSession(request);

		if (null == id || id <= 0) {
			throw new BizzException(BizzException.error_code_invalid_params, "二维码id错误！");
		}

		if (null == qcname) {
			throw new BizzException(BizzException.error_code_invalid_params, "二维码批次错误！");
		}
		String fileName = "组合二维码《" + qcname + "》明细下载";

		Integer companyid =  userSession.getCompanyId();
		
		String tmpfilefullname = picStoragePath + "/downloadfile/"+companyid+"_"+id+"_" + fileName + ".txt";

		File temf = new File(tmpfilefullname);
		if(temf.exists()){
			temf.delete();
		}
		if (!temf.exists()) {
			if (!temf.getParentFile().exists()) {
				temf.getParentFile().mkdirs();
			}
			temf.createNewFile();

			List<Map<String, Object>> qrcodelist = qrcodeService.queryQrcodeGroupInfoForDownload(id, userSession);
			String tmp_puuid = "";
			List<Map<String, Object>> tlist = null;

			Map<String, Object> mymap = new HashMap<String, Object>();
			for (Map<String, Object> map : qrcodelist) {
				Long tid = NumberUtils.toLong(map.get("id").toString(), 0L);
				byte type = NumberUtils.toByte(map.get("type").toString(), (byte) 0);
				if (0 == type) {
					String uuid = map.get("uuid").toString();
					String p_uuid = map.get("p_uuid").toString();
					String w_uuid = map.get("w_uuid").toString();
					if (p_uuid.equals(tmp_puuid)) {
						tlist = (List<Map<String, Object>>) mymap.get(p_uuid);
					} else {
						tlist = new ArrayList<Map<String, Object>>();
					}

					Map<String, Object> tmap1 = new HashMap<String, Object>();
					tmap1.put("tid", tid);
					tmap1.put("uuid", uuid);
					tmap1.put("w_uuid", w_uuid);
					tlist.add(tmap1);
					mymap.put(p_uuid, tlist);
					tmp_puuid = p_uuid;
				}
			}
			FileWriter fw = null;
			BufferedWriter writer = null;
			try {
				fw = new FileWriter(tmpfilefullname);
				writer = new BufferedWriter(fw);
				String sb = null;
				// 0000000001，http://scan.vats.com.cn/s/2/a1ff8a3321f94986b432384a3da4b9fc
				for (Map<String, Object> map : qrcodelist) {
					Long tid = NumberUtils.toLong(map.get("id").toString(), 0L);
					byte type = NumberUtils.toByte(map.get("type").toString(), (byte) -1);
					if (1 == type) {
						sb = String.valueOf(tid);
						int length = sb.length();
						for (int a = 11; a > length; a--) {
							sb = "0" + sb;
						}
						String uuidstr = map.get("uuid").toString();
						// 5 代表箱码物流码
						String str=sb + "," + qrcode_valid_url + 5 + "/" + map.get("w_uuid").toString();
						tlist = (List<Map<String, Object>>) mymap.get(uuidstr);
						for (Map<String, Object> tmap2 : tlist) {
							Long tid2 = NumberUtils.toLong(tmap2.get("tid").toString(), 0L);
							String uuidstr2 = tmap2.get("w_uuid").toString();
							sb = String.valueOf(tid2);
							int length2 = sb.length();
							for (int b = 11; b > length2; b--) {
								sb = "0" + sb;
							}
							// 4 代表瓶码物流码
							writer.write(str +"," + sb + "," + qrcode_valid_url + 4 + "/" + uuidstr2 + "\r\n");
//							writer.write("\r\n");// 换行
						}
					}

				}
				//System.out.println("换行换行换行-----------");
				writer.newLine();// 换行
				writer.flush();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					writer.close();
					fw.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

		}

		// 更新下载状态
		qrcodeService.updateGroupDownlaodState(id);

		InputStream is = new FileInputStream(tmpfilefullname);
		// 设置response参数，可以打开下载页面
		response.reset();
		response.setContentType("application/vnd.ms-excel;charset=utf-8");
		response.setHeader("Content-Disposition",
				"attachment;filename=" + new String((fileName + ".txt").getBytes(), "iso-8859-1"));
		ServletOutputStream out = response.getOutputStream();
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			bis = new BufferedInputStream(is);
			bos = new BufferedOutputStream(out);
			byte[] buff = new byte[2048];
			int bytesRead;
			// Simple read/write loop.
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
				bos.flush();
			}
		} catch (final IOException e) {
			throw e;
		} finally {
			if (bis != null)
				bis.close();
			if (bos != null)
				bos.close();
		}
		return null;
	}
	/**
	 * @author kelan
	 * @date 2017年3月9日
	 * @param request
	 * @param response
	 * @param id
	 * @param qcname
	 * http://scan.vats.com.cn/s/2/a1ff8a3321f94986b432384a3da4b9fc  其中 2：代表历史普通码瓶码 （营销码）；3：代表历史普通码箱码 （物流码） ；4：组合码瓶码 物流码 ；5：代表组合码箱码（物流码）；6：代表普通码（营销码）7.普通码（物流码）
	 * @return 
	 * @throws IOException
	 */
	@GetMapping("/qrcodeshortgroup/download")
	public String qrcode_shortgroup_download(HttpServletRequest request, HttpServletResponse response, Integer id,
			String qcname) throws IOException {

		UserSession userSession = getUserSession(request);

		if (null == id || id <= 0) {
			throw new BizzException(BizzException.error_code_invalid_params, "二维码id错误！");
		}

		if (null == qcname) {
			throw new BizzException(BizzException.error_code_invalid_params, "二维码批次错误！");
		}
		String fileName = "组合二维码《" + qcname + "》明细下载";

		Integer companyid =  userSession.getCompanyId();
		
		String tmpfilefullname = picStoragePath + "/downloadfile/"+companyid+"_"+id+"_" + fileName + ".txt";

		File temf = new File(tmpfilefullname);
		if(temf.exists()){
			temf.delete();
		}
		if (!temf.exists()) {
			if (!temf.getParentFile().exists()) {
				temf.getParentFile().mkdirs();
			}
			temf.createNewFile();

			List<Map<String, Object>> qrcodelist = qrcodeService.queryQrcodeGroupInfoForDownload(id, userSession);
			String tmp_puuid = "";
			List<Map<String, Object>> tlist = null;

			Map<String, Object> mymap = new HashMap<String, Object>();
			for (Map<String, Object> map : qrcodelist) {
				Long tid = NumberUtils.toLong(map.get("id").toString(), 0L);
				byte type = NumberUtils.toByte(map.get("type").toString(), (byte) 0);
				if (0 == type) {
					String uuid = map.get("uuid").toString();
					String p_uuid = map.get("p_uuid").toString();
					String w_uuid = map.get("w_uuid").toString();
					if (p_uuid.equals(tmp_puuid)) {
						tlist = (List<Map<String, Object>>) mymap.get(p_uuid);
					} else {
						tlist = new ArrayList<Map<String, Object>>();
					}

					Map<String, Object> tmap1 = new HashMap<String, Object>();
					tmap1.put("tid", tid);
					tmap1.put("uuid", uuid);
					tmap1.put("w_uuid", w_uuid);
					tlist.add(tmap1);
					mymap.put(p_uuid, tlist);
					tmp_puuid = p_uuid;
				}
			}
			FileWriter fw = null;
			BufferedWriter writer = null;
			try {
				fw = new FileWriter(tmpfilefullname);
				writer = new BufferedWriter(fw);
				String sb = null;
				StringBuilder longurl = new StringBuilder();//新建营销字符串一个对象  
				// 0000000001，http://scan.vats.com.cn/s/2/a1ff8a3321f94986b432384a3da4b9fc
				JSONArray js = new JSONArray();
				for (Map<String, Object> map : qrcodelist) {
					Long tid = NumberUtils.toLong(map.get("id").toString(), 0L);
					byte type = NumberUtils.toByte(map.get("type").toString(), (byte) -1);
					if (1 == type) {
						sb = String.valueOf(tid);
						int length = sb.length();
						for (int a = 11; a > length; a--) {
							sb = "0" + sb;
						}
						String uuidstr = map.get("uuid").toString();
						// 5 代表箱码物流码
						String str=sb + "," + qrcode_valid_url + 5 + "/" + map.get("w_uuid").toString();
						tlist = (List<Map<String, Object>>) mymap.get(uuidstr);
						for (Map<String, Object> tmap2 : tlist) {
							Long tid2 = NumberUtils.toLong(tmap2.get("tid").toString(), 0L);
							String uuidstr2 = tmap2.get("w_uuid").toString();
							sb = String.valueOf(tid2);
							int length2 = sb.length();
							for (int b = 11; b > length2; b--) {
								sb = "0" + sb;
							}
							// 4 代表瓶码物流码
							if(longurl.length()<=0){
								longurl.append( str +"," + sb + "," + qrcode_valid_url + 4 + "/" + uuidstr2) ;
							}else{
								longurl.append("|" + str +"," + sb + "," + qrcode_valid_url + 4 + "/" + uuidstr2) ;
							}
						}
					}

				}
				String url = dApisgroupurl+"?token="+dApistoken;
				Map<String, Object> map = new HashMap<String, Object>();
//				System.out.println(longurl);
				map.put("url", longurl);
				map.put("prefix", "C");//短地址 组合码物流码标识
				String result = HttpClientUtil.requestPost(url, map);
				JSONArray jsonarray = null;
				if(result.indexOf("{")>=0&&result.indexOf("}")>=0){
					JSONObject retjs = JSONObject.parseObject(result);
					if(retjs.containsKey("code") && retjs.getInteger("code")==200){
						jsonarray = JSONArray.fromObject(retjs.get("data"));
					}
				}
				for(Object b :jsonarray){
					writer.write(b.toString());
					writer.write("\r\n");// 换行
				}
				writer.newLine();// 换行
				writer.flush();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					writer.close();
					fw.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

		}

		// 更新下载状态
		qrcodeService.updateGroupDownlaodState(id);

		InputStream is = new FileInputStream(tmpfilefullname);
		// 设置response参数，可以打开下载页面
		response.reset();
		response.setContentType("application/vnd.ms-excel;charset=utf-8");
		response.setHeader("Content-Disposition",
				"attachment;filename=" + new String((fileName + ".txt").getBytes(), "iso-8859-1"));
		ServletOutputStream out = response.getOutputStream();
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			bis = new BufferedInputStream(is);
			bos = new BufferedOutputStream(out);
			byte[] buff = new byte[2048];
			int bytesRead;
			// Simple read/write loop.
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
				bos.flush();
			}
		} catch (final IOException e) {
			throw e;
		} finally {
			if (bis != null)
				bis.close();
			if (bos != null)
				bos.close();
		}
		return null;
	}

}
